package com.dap.batch.controller;

import com.dap.batch.constant.BatchConstant;
import com.dap.batch.dao.IDaoService;
import com.dap.batch.entity.Result;
import com.dap.batch.enums.ResultEnum;
import com.dap.batch.exception.BatchCustomException;
import com.dap.batch.po.BatchGroupPo;
import com.dap.batch.po.BatchJobPo;
import com.dap.batch.po.BatchStepPo;
import com.dap.batch.service.IBatchGroupService;
import com.dap.batch.utils.ResultUtils;
import com.dap.dao.model.QueryResult;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @description: group控制类
 * @author: Fesine
 * @createTime:2017/9/27 11:02
 * @update:修改内容
 * @author: Fesine
 * @updateTime:2017/9/27 11:02
 */
@RestController
@RequestMapping("/v1")
public class BatchGroupController {

    private final static Logger logger = LoggerFactory.getLogger(BatchGroupController.class);



    private IDaoService daoService;
    private IBatchGroupService groupService;

    @Autowired
    public BatchGroupController(IDaoService daoService, IBatchGroupService groupService) {
        this.daoService = daoService;
        this.groupService = groupService;
    }

    /**
     * 支持任务组名和注册组进行查询
     * @param po
     * @param page
     * @param limit
     * @return
     */
    @ApiOperation(value = "获取任务组信息列表", httpMethod = "GET")
    @GetMapping("/groups")
    public Result list(BatchGroupPo po
            , @RequestParam(defaultValue = "1") Integer page
            ,@RequestParam(defaultValue = "10") Integer limit){
        String name = po.getName();
        String catalog = po.getCatalog();
        if (StringUtils.isEmpty(catalog)) {
            po.setCatalog(null);
        }
        if (!StringUtils.isEmpty(name)) {
            StringBuffer sb = new StringBuffer("%");
            sb.append(name).append("%");
            po.setName(sb.toString());
        } else {
            po.setName(null);
        }
        String mapper = BatchGroupPo.class.getName() + BatchConstant.SELECT_LIKE;
        QueryResult<BatchGroupPo> result = daoService.selectQueryResult(mapper,po,
                page, limit);
        if (result.getTotalrecord() == 0) {
            throw new BatchCustomException(ResultEnum.NOT_FOUND);
        }
        return ResultUtils.success(result);
    }

    @ApiOperation(value = "根据ID获取任务组信息", httpMethod = "GET")
    @GetMapping("/group/{id}")
    public Result get(@PathVariable String id) {
        BatchGroupPo po = new BatchGroupPo();
        po.setId(id);
        BatchGroupPo batchGroupPo = daoService.selectOne(po);
        return ResultUtils.success(batchGroupPo);
    }

    @ApiOperation(value = "添加任务组信息", httpMethod = "POST")
    @PostMapping("/group")
    public Result add(BatchGroupPo po){
        //将name赋值给id
        po.setId(po.getName());
        int i = daoService.insert(po);
        if (i == 0) {
            throw new BatchCustomException(ResultEnum.INVALID_REQUEST);
        }
        return ResultUtils.success(ResultEnum.CREATED);
    }

    @ApiOperation(value = "修改任务组信息", httpMethod = "PUT")
    @PutMapping("/group")
    public Result update(BatchGroupPo po){
        int i = daoService.update(po);
        if (i == 0) {
            throw new BatchCustomException(ResultEnum.NOT_FOUND);
        }
        return ResultUtils.success(ResultEnum.CREATED);
    }


    @ApiOperation(value = "删除任务组信息", httpMethod = "DELETE")
    @DeleteMapping("/group/{id}")
    public Result delete(@PathVariable String id){
        BatchJobPo jobPo = new BatchJobPo();
        jobPo.setGroupId(id);
        List<BatchJobPo> jobList = daoService.selectList(jobPo);
        //删除step
        if (!CollectionUtils.isEmpty(jobList)) {
            for (BatchJobPo po : jobList) {
                BatchStepPo stepPo = new BatchStepPo();
                stepPo.setJobId(po.getId());
                daoService.delete(stepPo);
            }
        }
        //删除job
        daoService.delete(jobPo);
        //删除group
        BatchGroupPo po = new BatchGroupPo();
        po.setId(id);
        int i = daoService.delete(po);
        if (i == 0) {
            throw new BatchCustomException(ResultEnum.NOT_FOUND);
        }
        return ResultUtils.success(ResultEnum.DELETED);
    }

    @ApiOperation(value = "启动任务组", httpMethod = "POST")
    @PostMapping("/group/start/{id}")
    public Result start(@PathVariable String id){
        try {
            Long start = groupService.start(id);
            return ResultUtils.success(start);
        } catch (Exception e) {
            logger.error("【启动失败】",e);
            throw new BatchCustomException(ResultEnum.INTERNAL_SERVER_ERROR);
        }

    }
}
